package com.volatileshooter.state.command;

import java.util.Hashtable;
import java.util.Set;

import de.lessvoid.nifty.controls.console.ConsoleCommandHandler;

/**
 * CommandParser.
 * @author void
 */
public class CommandParser implements ConsoleCommandHandler {

	/**
	 * command store.
	 */
	private Hashtable < String, Command > commands = new Hashtable < String, Command >();

	/**
	 * out.
	 */
	private Output out;

	/**
	 * set output.
	 * @param output Output
	 */
	public void setOutput(final Output output) {
		out = output;
	}

	/**
	 * register command.
	 * @param command command to register
	 */
	public void registerCommand(final String name, final Command command) {
		commands.put(name, command);
	}

	/**
	 * find a command by name in the registered commands.
	 * @param name name of the command to find
	 * @return command or null
	 */
	public Command findCommandByName(final String name) {
		return commands.get(name);
	}

	/**
	 * execute.
	 * @param line line
	 */
	public void execute(final String line) {
		String[] args = line.split(" ");
		if (args.length > 0) {
			String commandName = args[0];
			Command command = findCommandByName(commandName);
			if (command != null) {
				System.out.println("execute command: " + commandName + "(" + getArgsLogOutput(args) + ")");
				out.write(command.execute(args));
			} else {
				out.write("command not understood o_O");
			}
		}
	}

	/**
	 * get all registered commands.
	 */
	public Set < String > getCommands() {
		return commands.keySet();
	}

	/**
	 * get given argument array as a log output string.
	 * @param args argument array
	 * @return log string
	 */
	private String getArgsLogOutput(final String[] args) {
		if (args == null || args.length == 0) {
			return "";
		} else {
			StringBuffer out = new StringBuffer();
			out.append(args[0]);
			for (int i=1; i<args.length; i++) {
				out.append("," + args[i]);	
			}
			return out.toString();
		}
	}
}
